<template>
  <view class="comp__avatar">
    <image
      class="comp__avatar-img"
      :style="imageStyle"
      :src="imageSrc"
      mode="aspectFit"
      @error="handleError"
      @click="handleClick"
    />
  </view>
</template>
 
<script>
import { DEFAULT_AVATAR } from '@/contants';

export default {
  props: {
    src: {
      type: String,
      default: DEFAULT_AVATAR,
    },
    size: {
      type: [String, Number],
      default: '60rpx',
    },
    round: {
      type: Boolean,
      default: true,
    },
  },

  data() {
    return {
      imageSrc: '',
    };
  },

  computed: {
    imageStyle() {
      const size = typeof this.size === 'number' ? `${this.size}px` : this.size;
      const borderRedius = this.round ? '50%' : 'none';
      return `width: ${size}; height: ${size}; border-radius: ${borderRedius}`;
    },
  },

  watch: {
    src(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.imageSrc = newValue || DEFAULT_AVATAR;
      }
    },
  },

  methods: {
    handleClick() {
      this.$emit('click');
    },

    handleError() {
      this.imageSrc = DEFAULT_AVATAR;
    },
  },

  created() {
    this.imageSrc = this.src || DEFAULT_AVATAR;
  },
};
</script>

<style lang='scss'>
</style>
